import Router from 'koa-router';
import { Context } from 'koa';
import { Rules } from 'async-validator';
import validate from '../../utils/validate';
import { signature } from '../../utils/jwt';
import ResponseOk from '../../utils/ResponseOk';
import PassPortService from '../../service/PassPortService';
import { isNull } from 'lodash-es';

const router = new Router();
router.post('/login', async (ctx: Context) => {
  const rules: Rules = {
    username: [{ type: 'string', required: true, message: '姓名必填' }],
    password: [{ type: 'string', required: true, message: '密码必填' }],
  };

  const { data, error } = await validate(ctx, rules);
  if (!isNull(error)) {
    throw new global.errs.ParameterException(error, 400);
  }
  const user = await PassPortService.login(data.username, data.password);

  const token = signature({ userId: user.id });
  ctx.body = ResponseOk.success({
    token: token,
  });
});
export default router;
